// https://juejin.cn/post/7012622147726082055
// scripts/publish.js
import path from 'path'
import { globby, globbySync } from 'globby'
import EventEmitter from 'events'
import inquirer from 'inquirer'
import fs from 'fs-extra'
import shelljs from 'shelljs'
// import { execa, execaCommand, execaCommandSync } from 'execa'
const cwd = process.cwd()

const getPackagePath = () => {
  const packagePaths = globbySync('./packages', {
    cwd,
    onlyDirectories: true,
    deep: 1,
  })

  console.log(path.resolve(cwd, '../packages'), cwd)

  return packagePaths.map((item) => item.replace('../', ''))
}

const choosePackage = async (packages) => {
  return await inquirer.prompt({
    type: 'list',
    name: 'packages',
    message: '选择你要发布的包:',
    choices: [...packages],
  })
}


async function selectedVersion(version) {
  const [ one, two, three ] = version.split('.');

  const choices = {
    type: 'list',
    name: 'packages',
    message: '选择包发布的版本:',
    choices: [
      version,
      `${ one }.${ two }.${ +three + 1 }`,
      `${ one }.${ +two + 1 }.0`,
      `${ +one + 1 }.0.0`,
    ],
  }
  return inquirer.prompt(choices)
}

function newPackageJson(packages) {
  const {
    login,
    devDependencies,
    email,
    scripts,
    eslintConfig,
    browserslist,
    ...config
  } = packages;

  return config
}

/**
 * package.publish.json
 * 作用为，如果存在，则使用这个json作为发布库的 package.json，以过滤包的太多无用的依赖。
 * @return {Promise<void>}
 */
const publish = async () => {
  const packagePaths = getPackagePath();
  const { packages } = await choosePackage(packagePaths);
  const subPath = path.resolve(cwd, packages);

  let pkg = {};
  const hasPkgJson = await fs.exists(path.resolve(cwd, packages, 'package.json'))

  if (!hasPkgJson) {
    console.error('没有找到 package.json !');
    return;
  } else {
    pkg = await fs.readJson(path.resolve(cwd, packages, 'package.json'), "utf-8");
  }

  let newPackages = {};
  const hasPublishJson = await fs.exists(path.resolve(cwd, packages, 'package.publish.json'));
  if (hasPublishJson) {
    console.log('使用 package.publish.json 发布')
    newPackages = await fs.readJson(path.resolve(cwd, packages, 'package.publish.json'), "utf-8");
  } else {
    console.log('使用 package.json 发布')
    newPackages = newPackageJson(pkg);
  }

  try {
    const { packages: newVersion } = await selectedVersion(pkg.version)
    console.log('发布版本: ', newVersion)
    newPackages.version = newVersion
    pkg.version = newVersion

    console.log('创建文件夹路径: “dest/lib”')
    await fs.ensureDir(path.resolve(subPath, `dest/lib`));

    console.log('创建 newPackages')
    await fs.writeJSON(path.resolve(subPath, `dest/package.json`), newPackages, { spaces: 2 });

    console.log('修改 package.json')
    await fs.writeJSON(path.resolve(subPath, `package.json`), pkg, { spaces: 2 });
    if (hasPublishJson) {
      console.log('修改 package.publish.json')
      await fs.writeJSON(path.resolve(subPath, `package.publish.json`), newPackages, { spaces: 2 });
    }

    console.log('复制 lib ——> dest/lib')
    await fs.copy(
      path.resolve(subPath, `lib`),
      path.resolve(subPath, `dest/lib`),
    )

    /*console.log('复制 types ——> dest/types')
    await fs.copy(
      path.resolve(subPath, `types`),
      path.resolve(subPath, `dest/types`),
    )*/

    console.log('执行发布命令: => ', `cd ${path.resolve(subPath, `dest`)} && npm publish`)
    shelljs.exec(`cd ${path.resolve(subPath, `dest`)} && npm publish`)
  } catch (error) {
    console.error(error)
  }
}

publish()

